<!DOCTYPE html>
<html lang="zh-cn">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>文件下载器</title>
</head>
<body>
  <script type="text/javascript">
    function textDecoderStream() {
      const decoder = new TextDecoder()
      return new TransformStream({
        transform(chunk, controller) {
          controller.enqueue(decoder.decode(chunk)+'a');
        }
      })
    }

    function upperCaseStream() {
      return new TransformStream({
        transform(chunk, controller) {
          controller.enqueue(chunk.toUpperCase());
        },
      });
    }

    function appendToDOMStream(el) {
      return new WritableStream({
        write(chunk) {
          document.body.append(chunk);
        },
        close(controller) {
          console.log('close')
          // 将会在流写入完成时调用
        },
        abort(reason) {
          console.log('abort reason--->', reason)
          // 将会在流强制关闭时调用，此时流会进入一个错误状态，不能再写入
        }
      });
    }

    fetch('./word.txt').then((response) =>
      response.body
        .pipeThrough(new TextDecoderStream())
        .pipeThrough(upperCaseStream())
        .pipeTo(appendToDOMStream(document.body))
    );
  </script>
</body>
</html>